package com.giantlizard.cloud.utils;

import com.giantlizard.cloud.base.entity.LogRecordData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
public class RabbitSendLogRecord {

    private final RabbitTemplate rabbitTemplate;
    public RabbitSendLogRecord(@Lazy RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    private final RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, s) -> {
        log.info("correlationData={}",correlationData);
        log.info("ack={}",ack);
        if (ack){
            log.info("消息已处理");
        }else {
            log.error("处理异常:{}"+ s);
        }
    };
    private RabbitTemplate.ReturnsCallback callback = (ReturnedMessage returned)
            -> {
        log.info("找不到对应的队列");
    };

    public void sendLogRecord(LogRecordData message ) {

        rabbitTemplate.setConfirmCallback(confirmCallback);

        rabbitTemplate.setReturnsCallback(callback);

        //消息唯一id
        CorrelationData correlationData = new CorrelationData("giantlizard-log"+ LocalDateTime.now() + System.currentTimeMillis());

        rabbitTemplate.convertAndSend("giantlizard-log","log.record",message,correlationData);

    }
}
